package com.zxl.yjb.activity.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.zxl.yjb.GlideApp;
import com.zxl.yjb.R;
import com.zxl.yjb.activity.LoginActivity;
import com.zxl.yjb.activity.MainActivity;
import com.zxl.yjb.activity.home.position.PositionSelectActivity;
import com.zxl.yjb.adapter.FullyGridLayoutManager;
import com.zxl.yjb.adapter.GridImageAdapter;
import com.zxl.yjb.app.AppManager;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.FileUploadBean;
import com.zxl.yjb.bean.LocalMediaExtend;
import com.zxl.yjb.bean.LoginSucessBean;
import com.zxl.yjb.bean.MessageEvent;
import com.zxl.yjb.http.HostUrl;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.utils.PickerViewUtils;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.ToastUtils;
import com.zxl.yjb.widget.CircleImageView;
import com.zxl.yjb.widget.SwitchButton;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FillInfoActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_page_title)
    TextView tvPageTitle;
    @BindView(R.id.iv_my_header)
    CircleImageView ivMyHeader;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.ll_nickname)
    LinearLayout llNickname;
    @BindView(R.id.tv_gender)
    TextView tvGender;
    @BindView(R.id.ll_gender)
    LinearLayout llGender;
    @BindView(R.id.ll_position)
    LinearLayout ll_position;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.ll_birthday)
    LinearLayout llBirthday;
    @BindView(R.id.tv_signature)
    TextView tvSignature;
    @BindView(R.id.ll_signature)
    LinearLayout llSignature;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.switch_button)
    SwitchButton switchButton;
    private int maxSelectNum = 8;
    private List<LocalMedia> selectList = new ArrayList<>();//本地显示用
    private List<LocalMedia> uploadList = new ArrayList<>();//本地显示用
    private List<LocalMedia> selectHeadImgList = new ArrayList<>();
    private GridImageAdapter adapter;
    private final int CHOOSE_HEADIMG_REQUEST = 1001;
    private final int UPDATA_NICKNAME_REQUEST = 1002;
    private final int UPDATA_SIGNATURE_REQUEST = 1003;
    private boolean[] booleen = {true, true, true, false, false, false};
    private LoginSucessBean loginSucessBean;
    private boolean userDataChange;
    private String photos = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acticity_fillinfo);
        ButterKnife.bind(this);
        Object bean = SaveBeanUtil.getBean(this, Const.VIPINFO);
        if (bean != null) {
            loginSucessBean = (LoginSucessBean) bean;
        }
        initView();
        initEvent();
        getPhotoWall();
    }

    @Override
    protected void initView() {
        tvPageTitle.setText(R.string.ziliaosheding);
        if (loginSucessBean == null)
            return;
        tvNickname.setText(loginSucessBean.getNickname());
        int sex = loginSucessBean.getSex();
        tvGender.setText(sex == 0 ? "" : sex == 1 ? "男" : "女");
        tvBirthday.setText(loginSucessBean.getBirthday());
//                tvSignature.setText(loginSucessBean.get);
        if (!TextUtils.isEmpty(loginSucessBean.getFace_img())) {
            GlideApp.with(FillInfoActivity.this).load(HostUrl.HOST + loginSucessBean.getFace_img()).into(ivMyHeader);
        }
        String state = loginSucessBean.getReceive_jpush();
        if (!TextUtils.isEmpty(state)) {
            if ("0".equals(state)) {
                switchButton.setChecked(false);
            } else if ("1".equals(state)) {
                switchButton.setChecked(true);
            }
        }
    }

    //获取照片墙
    private void getPhotoWall() {
        DataManager dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("uid", loginSucessBean.getUid() + "");
        ObserverOnNextListener<ArrayList<String>> listener = new ObserverOnNextListener<ArrayList<String>>() {
            @Override
            public void onNext(ArrayList<String> strings) {

                for (int i = 0; i < strings.size(); i++) {
                    LocalMediaExtend localMediaExtend = new LocalMediaExtend();
                    localMediaExtend.setPath(strings.get(i));
                    localMediaExtend.setWebUrl(true);
                    selectList.add(localMediaExtend);
                }

                adapter.notifyDataSetChanged();
            }
        };
        dataManager.photowall_list(new ProgressObserver<ArrayList<String>>(listener, FillInfoActivity.this), map);
    }

    //上传图片文件
    private void uploadPhotoWallPic() {
        uploadList.clear();
        for (int i = 0; i < selectList.size(); i++) {
            if (/*(selectList.get(i).getWidth()!=0||selectList.get(i).getHeight()!=0)&&*/(selectList.get(i).isCompressed() || selectList.get(i).isCut())) {
                uploadList.add(selectList.get(i));
            }
        }

        if (uploadList.size() > 0) {
            DataManager dataManager = new DataManager();
            ObserverOnNextListener<FileUploadBean> listener = new ObserverOnNextListener<FileUploadBean>() {
                @Override
                public void onNext(FileUploadBean fileUploadBean) {
                    haneldPicPath(fileUploadBean);
                    uploadPhotoWall();
                }
            };
            dataManager.uploadMultiPicture(new ProgressObserver<FileUploadBean>(listener, this), uploadList);
        } else {
            haneldPicPath(null);
            uploadPhotoWall();
        }

    }

    //拼接图片地址参数
    private void haneldPicPath(FileUploadBean fileUploadBean) {
        photos = "";
        if (selectList.size() > 0) {
            for (int i = 0; i < selectList.size(); i++) {
                if (!(selectList.get(i).isCompressed() || selectList.get(i).isCut())) {
                    photos += selectList.get(i).getPath() + ",";
                }
            }
        } else {
            photos += "";
        }

        if (fileUploadBean != null) {
            ArrayList<String> picList = fileUploadBean.getUrls();
            if (picList != null && picList.size() > 0) {
                for (int i = 0; i < picList.size(); i++) {
                    photos += picList.get(i) + ",";
                }
            } else {
                photos += "";
            }
        }


        if (photos.endsWith(",")) {
            photos = photos.substring(0, photos.length() - 1);
        }


    }

    //上传图片地址
    private void uploadPhotoWall() {
        DataManager dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("photos", photos);
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object o) {
                finish();
            }
        };
        dataManager.photowall_add_update(new ProgressObserver<Object>(listener, FillInfoActivity.this) {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                finish();
                ToastUtils.show(FillInfoActivity.this, "照片墙更新失败");
            }
        }, map);
    }


    private void setNoReceive(final String param) {
        DataManager dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("open0close1", param);
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object o) {
                ToastUtils.show(getApplicationContext(), "0".equals(param) ? "消息免打扰已关闭" : "消息免打扰已开启");
                EventBus.getDefault().post(new MessageEvent("refreshUserInfo"));
            }
        };
        dataManager.set_no_receive_order_jpush(new ProgressObserver<Object>(listener, this), map);
    }

    private void initEvent() {
//        switchButton.setChecked(true);
        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
//                ToastUtils.show(getApplicationContext(), isChecked ? "kai" : "guan");
                setNoReceive(isChecked ? "1" : "0");
            }
        });
        FullyGridLayoutManager manager = new FullyGridLayoutManager(FillInfoActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                DisplayUtil.openAlbum(FillInfoActivity.this, maxSelectNum - selectList.size(), null, PictureConfig.CHOOSE_REQUEST);
            }
        };
        adapter = new GridImageAdapter(FillInfoActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            List<LocalMedia> tempMediaList = new ArrayList<>();
                            for (LocalMedia selectListMedia : selectList) {
                                LocalMedia tempLocalMedia = new LocalMedia();
                                if (!(selectListMedia.isCompressed() || selectListMedia.isCut())) {
                                    tempLocalMedia.setPath(HostUrl.HOST + selectListMedia.getPath());
                                } else {
                                    tempLocalMedia.setPath(selectListMedia.getPath());
                                }
                                tempMediaList.add(tempLocalMedia);
                            }
                            //PictureSelector.create(MainActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(FillInfoActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, tempMediaList);
                            break;
                        case 2:
                            PictureSelector.create(FillInfoActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            PictureSelector.create(FillInfoActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
    }


    @OnClick({R.id.iv_back, R.id.ll_my_info, R.id.ll_nickname, R.id.ll_gender,
            R.id.ll_birthday, R.id.ll_signature, R.id.btn_switch_account, R.id.ll_position})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_back:
                /*if (userDataChange)
                    EventBus.getDefault().post(new MessageEvent("refreshUserInfo"));
                uploadPhotoWallPic();*/
                Intent intent1 = new Intent(FillInfoActivity.this,LoginActivity.class);
                startActivity(intent1);
                finish();
                break;
            case R.id.ll_my_info:
                DisplayUtil.openAlbum(this, 1, selectHeadImgList, CHOOSE_HEADIMG_REQUEST);
                break;
            case R.id.ll_nickname:
                intent.setClass(FillInfoActivity.this, UpdataNickNameActivity.class);
                intent.putExtra("old_nick_name", tvNickname.getText().toString());
                startActivityForResult(intent, UPDATA_NICKNAME_REQUEST);
                break;
            case R.id.ll_gender:
                String[] genderArray = {"男", "女"};
                DisplayUtil.diaplayDialogMydata(this, "性别", genderArray, tvGender, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String sex = tvGender.getText().toString();
                        boolean whichSex = "男".equals(sex);
                        upDataUserInfo(3, whichSex ? "1" : "2");
                    }
                });
                break;
            case R.id.ll_birthday:
                PickerViewUtils.timePickerViewWithRangeAndDate(new OnTimeSelectListener() {//时间选择后的回调
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        tvBirthday.setText(sdf.format(date));
                        upDataUserInfo(4, sdf.format(date));
                    }
                }, 1940, 2049, "2000-01-01", booleen);//调用选择器
                break;
            case R.id.ll_signature:
                intent.setClass(FillInfoActivity.this, UpdataSignatureAcitivity.class);
                intent.putExtra("old_signature", tvSignature.getText().toString());
                startActivityForResult(intent, UPDATA_SIGNATURE_REQUEST);
                break;
            case R.id.btn_switch_account://提交
                submit();
                break;
            case R.id.ll_position://退出登陆，切换账户
                if (loginSucessBean.getNickname().equals("用户")) {
                    ToastUtils.show(FillInfoActivity.this, "请设置昵称");
                    return;
                }
                if (loginSucessBean.getSex() == 0) {
                    ToastUtils.show(FillInfoActivity.this, "请设置性别");
                    return;
                }
                if (loginSucessBean.getBirthday().equals("0")) {
                    ToastUtils.show(FillInfoActivity.this, "请设置生日");
                    return;
                }
                /*DataManager dataManager = new DataManager();
                dataManager.getUserInfo(new ProgressObserver<LoginSucessBean>(new ObserverOnNextListener<LoginSucessBean>() {
                    @Override
                    public void onNext(LoginSucessBean loginSucessBean) {
                        if (loginSucessBean == null)
                            return;
                        if (loginSucessBean.getFillMyInfo().equals("1")){
                            ToastUtils.show(FillInfoActivity.this,"信息填写不完整，请核对后重新提交");
                            return;
                        } else {
                            SaveBeanUtil.putBean(getApplicationContext(), Const.VIPINFO, loginSucessBean);
                            Intent intent1 = new Intent(FillInfoActivity.this,MainActivity.class);
                            startActivity(intent1);
                            finish();
                        }


                    }
                }, this), loginSucessBean.getUid() + "");*/
                SaveBeanUtil.putBean(getApplicationContext(), Const.FILLMYINFO, "0");
                Intent intent2 = new Intent(FillInfoActivity.this,MainActivity.class);
                startActivity(intent2);
                finish();

                break;
        }
    }

    /**
     * 提交
     */
    private void submit() {

       /* if (TextUtils.isEmpty(loginSucessBean.getFace_img())){
            ToastUtils.show(getApplicationContext(),"请上传头像后，再提交！");
            return;
        } else*/ if (TextUtils.isEmpty(tvNickname.getText().toString())||tvNickname.getText().toString().equals("用户")) {
            ToastUtils.show(getApplicationContext(),"请设置昵称后，再提交！");
            return;
        } else if (TextUtils.isEmpty(tvGender.getText().toString())) {
            ToastUtils.show(getApplicationContext(),"请选择性别后，再提交！");
            return;
        } else if (TextUtils.isEmpty(tvBirthday.getText().toString())||tvBirthday.getText().toString().equals("0")) {
            ToastUtils.show(getApplicationContext(),"请选择出生日期后，再提交！");
            return;
        }
        DataManager dataManager = new DataManager();
        dataManager.upDateUserInfo(new ProgressObserver<Object>(new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object callBack) {
                ToastUtils.show(getApplication(), "修改成功！");
                EventBus.getDefault().post(new MessageEvent("refreshUserInfo"));
                userDataChange = true;
                SaveBeanUtil.putBean(FillInfoActivity.this, Const.VIPINFO, loginSucessBean);
                SaveBeanUtil.putBean(getApplicationContext(), Const.FILLMYINFO, "0");
                startActivity(new Intent(FillInfoActivity.this,MainActivity.class).putExtra("idstatus", "0"));
                finish();
                }
            } ,FillInfoActivity.this),loginSucessBean);
    }

    /**
     * 图片上传
     *
     * @param imgPath
     */

    private void uploadPic(List<LocalMedia> imgPath) {
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<FileUploadBean> listener = new ObserverOnNextListener<FileUploadBean>() {
            @Override
            public void onNext(FileUploadBean fileUploadBean) {
                String faceImgPath = fileUploadBean.getUrls().get(0);
                if (!TextUtils.isEmpty(faceImgPath))
                    upDataFiceImg(2, faceImgPath);
            }
        };
        dataManager.uploadMultiPicture(new ProgressObserver<FileUploadBean>(listener, this), imgPath);
    }

    private void upDataFiceImg(int i, final String faceImgPath) {
        DataManager dataManager = new DataManager();
        dataManager.xgFaceimg(new ProgressObserver<Object>(new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object callBack) {
                loginSucessBean.setFace_img(faceImgPath);
                SaveBeanUtil.putBean(FillInfoActivity.this, Const.VIPINFO, loginSucessBean);
            }
        } ,FillInfoActivity.this),faceImgPath);

    }

    /**
     * 向服务器上传个人信息
     */
    private void upDataUserInfo(final int type, final String userInfo) {
        switch (type) {
            case 1:
                loginSucessBean.setNickname(userInfo);
                break;
            case 2:
                loginSucessBean.setFace_img(userInfo);
                break;
            case 3:
                loginSucessBean.setSex(Integer.parseInt(userInfo));
                break;
            case 4:
                loginSucessBean.setBirthday(userInfo);
                break;
        }
       /* switch (type) {
            case 1:
                dataManager.xgNickName(objectProgressObserver, userInfo);
                break;
            case 2:
                dataManager.xgFaceimg(objectProgressObserver, userInfo);
                break;
            case 3:
                dataManager.xgGender(objectProgressObserver, userInfo);
                break;
            case 4:
                dataManager.xgBirthday(objectProgressObserver, userInfo);
                break;

        }*/
    }

    //修改im当前用户信息
  /*  private void upDataImInfo(String nickName, String facePath) {
        //执行一次就可以
        if (tem == 0) {
            String currentFaceImgPath;
            if (TextUtils.isEmpty(facePath)) {//没有获取最新上传的头像，则用之前的头像
                currentFaceImgPath = (String) SPUtil.get(getApplication(), Const.SEALTALK_LOGING_PORTRAIT, "");
            } else {//头像更新成功，使用返回的头像路径拼接url
                currentFaceImgPath = HostUrl.HOSTPIC + facePath;
            }
            String id = (String) SPUtil.get(getApplication(), SEALTALK_LOGIN_ID, "");
            RongIM.getInstance().setCurrentUserInfo(new UserInfo(id, nickName, Uri.parse(currentFaceImgPath)));
            tem++;
        }
    }*/


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:

//                    selectList = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(PictureSelector.obtainMultipleResult(data));
                    for (LocalMedia selectMedia : selectList) {
                        Log.i("图片-----》", selectMedia.getPath());
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
                case CHOOSE_HEADIMG_REQUEST://选择头像
                    // 图片选择结果回调
                    selectHeadImgList = PictureSelector.obtainMultipleResult(data);
                    if (selectHeadImgList.size() == 0) {
                        return;
                    }
                    LocalMedia media = selectHeadImgList.get(0);
                    String compressPath = media.getCompressPath();
                    media.setPath(compressPath);
                    GlideApp.with(FillInfoActivity.this).load(compressPath).into(ivMyHeader);
                    uploadPic(selectHeadImgList);
                    break;
                case UPDATA_NICKNAME_REQUEST://更改昵称
                    if (data != null) {
                        String newNickName = data.getStringExtra("new_nick_name");
                        if (!TextUtils.isEmpty(newNickName) && !tvNickname.getText().toString().equals(newNickName)) {
                            tvNickname.setText(newNickName);
                            upDataUserInfo(1, newNickName);
                        }
                    }
                    break;
                case UPDATA_SIGNATURE_REQUEST://更改签名
                    if (data != null) {
                        String result = data.getStringExtra("new_signature");
                        if (!TextUtils.isEmpty(result)) {
                            tvSignature.setText(result);
                        }
                    }
                    break;
            }
        }
    }
}
